<route lang="json5"></route>

<script setup lang="ts">
import ViewContainer from "@/layouts/ViewContainer.vue";
import titleConfig from "./outbound.title";
import Form from "@/components/StorageForm/index";
import useScan from "@/hooks/useScan";
import { useMessage } from "wot-design-uni";
import { storageService } from "@/service/storage";
import Spin from "@/components/Spin/index.vue";
import { useScanStore, useToastStore } from "@/store";

const SCAN_STORE_OUT_ID = "OUTBOUND_SCAN";

const Basic = Form.BasicForm;
const List = Form.ScanListForm;
const Row = Form.CommonRow;
const Modal = Form.ConfirmModal;

const message = useMessage();
const toastStore = useToastStore();
const scanStore = useScanStore();

const outType = ref();

const modalVisible = ref<boolean>(false);
const loading = ref(false);

const basicRef = ref(null);

const listenScanRes = async (res) => {
	loading.value = true;
	try {
		const rs = await storageService.scanBox({ boxNumber: res });
		if (rs) {
			const arr = [];
			const { mainOrderNumber, transportationRouteList } = rs;
			transportationRouteList.map((item) => {
				arr.push({
					mainOrderNumber,
					transportationRoute: item.route,
					packageNumber: 1,
					allPackageNumber: item.remainPackageQuantity,
					weight: item.weight,
				});
			});
			modalConfig.value = arr;
			modalVisible.value = true;
		}
	} catch (error) {
		console.log(error);
	} finally {
		loading.value = false;
	}
};

useScan({
	scanCallback: listenScanRes,
	timeOutCallback: () => {
		toastStore.set("未识别，请核对条形码是否正确", "warning");
	},
});

// 尾程确认弹窗
const modalConfig = ref([]);

const scanList = ref([]);

const totalConfig = computed(() => {
	const _d = scanList.value;

	const total = _d.length;
	let totalPackageNumber = 0;
	let totalWeight = 0;
	let totalTrapNumber = 0;

	_d.forEach((item) => {
		totalPackageNumber += item.packageNumber;
		totalWeight += item.weight;
		totalTrapNumber += item.trap;
	});

	return [
		{
			label: "总计:",
			value: total,
		},
		{
			label: "总出库数:",
			value: totalPackageNumber,
		},
		{
			label: "总重:",
			value: totalWeight,
		},
		{
			label: "总托盘数:",
			value: totalTrapNumber,
		},
	];
});

// 选择尾程提交
const submitScanItem = (value) => {
	const _c = scanList.value;
	_c.push(value);
	scanList.value = _c;
};

// 返回
const handleBack = () => {
	uni.navigateBack();
};

// 确认
const handleConfirm = async () => {
	loading.value = true;
	try {
		const formRs = await basicRef.value?.validate();
		if (!formRs || !formRs.valid) {
			loading.value = false;
			// message.alert("基础信息未填写完整");
			toastStore.set("基础信息未填写完整", "warning");
			return;
		}
		if (scanList.value.length === 0) {
			loading.value = false;
			// message.alert("暂无出库信息");
			toastStore.set("暂无出库信息", "warning");

			return;
		}

		const _logisticsList = scanList.value.map((item) => ({
			mainOrderNumber: item.mainOrderNumber,
			outPackageQuantity: item.packageNumber,
			weight: item.weight,
			transportationRoute: item.transportationRoute,
			palletQuantity: item.trap,
		}));

		const params = {
			...basicRef.value?.getValues(),
			logisticsDetailList: _logisticsList,
			outType: outType.value == 1 ? "LOCAL" : "OUTSIDE"
		};

		const rs = await storageService.confirmOut(params);
		if (rs) {
			// message.alert("出库成功");
			toastStore.set("出库成功", "success");

			setTimeout(() => {
				uni.reLaunch({ url: "/pages/index/index" });
			}, 2000);
		}
	} catch (error) {
		console.log(error);
	}
};

onLoad((options) => {
	// const v = scanStore.get(SCAN_STORE_OUT_ID);
	let v = "UNIUNIUS202406230033LAX";
	if (v) {
		listenScanRes(v);
	} else if (options.id) {
		listenScanRes(options.id);
	} else {
		toastStore.set("暂无扫描信息,请重新扫描", "warning");
	}

	outType.value = options.outType;
});
</script>

<template>
	<ViewContainer :title="titleConfig" innerClass="outbound-page">
		<Spin :loading="loading" :full="true">
			<Basic ref="basicRef" :showTitle="true" type="edit" :unnessary="outType == 1" />
			<Row :config="totalConfig" class="mt" />
			<List title="出库信息" v-model:value="scanList" class="mt" :numberText="'出库数量'" />

			<view class="btn-group">
				<wd-button @click="handleBack" class="btn back" type="info" :round="false">返回</wd-button>
				<wd-button @click="handleConfirm" class="btn confirm" :round="false">确认出库</wd-button>
			</view>
		</Spin>
		<Modal v-model:visible="modalVisible" title="尾程确认" :data="modalConfig" @submit="submitScanItem" />
	</ViewContainer>
</template>

<style lang="less">
:deep(.outbound-page) {
	height: 1500px;

	.mt {
		margin-top: 30px;
	}

	.btn-group {
		display: flex;
		justify-content: center;
		margin: 50px 0;

		.btn {
			width: 45%;
			height: 100px;
		}
	}
}
</style>
